class AccountController < ApplicationController
  before_filter :sys_before_log

  #获取所有的账号信息
  def getAccounts
    total = Account.count
    accounts = Account.findPage(params[:start].to_i, params[:limit].to_i)
    jsonStr="{account:"+accounts.to_json()+",total:"+total.to_s+"}"
    render :text => jsonStr,:layout => false
  end

  def create
    begin
      account = Account.find_by_username params[:username]
      if account != nil
        info = '账号已存在，请更换！'
      else
        account = Account.new
        account.username = params[:username]
        account.password = params[:password]
        account.save!
        info = 'success'
      end
    rescue Exception => e
      logger.info e
      info = '创建异常'
    end

    result = "{success:true,info:\"#{info}\"}"
    render :text => result,:layout => false
  end

  def delete
    begin
      ids= params[:id][1..params[:id].length-2].split(',')
      Account.destroy(ids)
      info = 'success'
    rescue Exception=>e
      info = e.to_s
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

  #锁定或解锁，只允许锁定。
  def doLock
    ids= params[:id][1..params[:id].length-2].split(',')
    for id in ids
      account = Account.find(id)
      if account.is_locked == 1
        account.is_locked = 0
      else
        account.is_locked = 1
      end
      account.save!
    end
    info = "success"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
  

  def edit
    account = Account.find(params[:accountId])
    jsonStr = account.to_json()
    render :text=>jsonStr,:layout=>false
  end

  def update
    begin
      account = Account.find(params[:id])
      if account.username == params[:username].to_s
        account.password = params[:password]
        account.save
        info = 'success'
      else
        accountUser = Account.find_by_username params[:username]
        if accountUser == nil
          account.username = params[:username]
          account.password = params[:password]
          account.save
          info = 'success'
        else
          info = '该账号已存在，请更换！'
        end
      end
    rescue Exception=>e
      logger.info e
      info = '更新异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end
  
end
